package org.example.com.editor.command.workspaceCommand;

import org.example.com.editor.command.Command;
import org.example.com.editor.editor.Editor;
import org.example.com.editor.logger.LogManager;
import org.example.com.editor.ui.ConsoleUI;
import org.example.com.editor.workspace.Workspace;

import java.util.List;

public class InitCommand implements Command {
    private final LogManager logManager;

    public InitCommand(LogManager logManager) {
        this.logManager = logManager;
    }

    @Override
    public void execute(Workspace workspace, ConsoleUI ui) throws Exception {
        // 1. （格式：init <文件路径> 或 init <文件路径> with-log）
        String[] args = ui.getCommandArgs();
        if (args.length != 2 && args.length != 3) {
            ui.printError("用法：init <文件路径> [with-log]");
            return;
        }

        // 2. 解析参数：文件路径 + 是否启用日志（with-log可选）
        String filePath = args[1];
        boolean withLog = false;
        if (args.length == 3) {
            if (!"with-log".equals(args[2])) {
                ui.printError("无效可选参数：仅支持\"with-log\"作为可选参数");
                return;
            }
            withLog = true;
        }

        // 3. 调用工作区初始化方法
        try {
            workspace.initFile(filePath, withLog);
            // 4. 输出成功信息（区分是否带日志标记）
            String logHint = withLog ? "（已添加# log标记，打开时自动启用日志）" : "";
            ui.printInfo("已创建新缓冲文件：" + filePath + logHint);
            ui.printInfo("当前活动文件：" + filePath);
            Editor editor = workspace.getActiveEditor();
            List<String> content = editor.getContent();
            String firstLine = content.isEmpty() ? null : content.get(0);
            logManager.checkAndEnableLogForFile(filePath, firstLine);
            logManager.onCommandExecuted(filePath, args);
        } catch (IllegalArgumentException e) {
            ui.printError(e.getMessage());
        }
    }

    @Override
    public String getName() {
        return "init";
    }
}